package com.bt7274.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import jakarta.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * JWT token 管理工具
 */
@Component
public class JwtUtil {

    private static String secret;
    private static long expiration;

    @Value("${jwt.secret}")
    public void setSecret(String secret) {
        JwtUtil.secret = secret;
    }

    @Value("${jwt.expiration}")
    public void setExpiration(long expiration) {
        JwtUtil.expiration = expiration;
    }

    /**
     * 生成JWT Token
     * @param userId 用户ID
     * @param username 用户名
     * @param role 角色
     * @return Token字符串
     */
    public static String generateToken(String userId, String username, Integer role) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", userId);
        claims.put("username", username);
        claims.put("role", role);


        return Jwts.builder()
                .setClaims(claims)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + expiration * 1000))
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    /**
     * 解析并验证Token，获取所有Claims
     * @param token JWT字符串
     * @return Claims Map，验证失败返回null
     */
    public static Claims getClaimsFromToken(String token) {
        return Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
    }

    /**
     * 从Claims中获取用户ID
     * @param claims Claims Map
     * @return 用户ID
     */
    public static String getUserIdFromClaims(Claims claims) {
        return claims.get("userId").toString();
    }

    /**
     * 从Claims中获取用户名
     * @param claims Claims Map
     * @return 用户名
     */
    public static String getUsernameFromClaims(Claims claims) {
        return claims.get("username").toString();
    }

    /**
     * 从Claims中获取角色
     * @param claims Claims Map
     * @return 角色
     */
    public static Integer getRoleFromClaims(Claims claims) {
        return Integer.valueOf(claims.get("role").toString());
    }

    /**
     * 校验Token是否过期
     * @param claims JWT claims
     * @return true过期,false未过期或验证失败
     */
    public static boolean validateExpiration(Claims claims) {
        return !claims.getExpiration().before(new Date());
    }

    /**
     * 从HTTP请求头中获取Token
     * @param request Http请求
     * @return token字符串或null
     */
    public static String getTokenFromRequest(HttpServletRequest request) {
        String authorization = request.getHeader("Authorization");
        if (authorization != null && authorization.startsWith("Bearer ")) {
            return authorization.substring(7);
        }
        return null;
    }

    /**
     * 从请求中获取用户ID
     */
    public static String getUserIdFromRequest(HttpServletRequest request) {
        String token = getTokenFromRequest(request);
        Claims claims = getClaimsFromToken(token);
        return getUserIdFromClaims(claims);
    }

    /**
     * 从请求中获取用户名
     */
    public static String getUsernameFromRequest(HttpServletRequest request) {
        String token = getTokenFromRequest(request);
        Claims claims = getClaimsFromToken(token);
        return getUsernameFromClaims(claims);
    }

    /**
     * 从请求中获取角色
     */
    public static Integer getRoleFromRequest(HttpServletRequest request) {
        String token = getTokenFromRequest(request);
        Claims claims = getClaimsFromToken(token);
        return getRoleFromClaims(claims);
    }
}
